package com.mbbb.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mbbb.yygh.hosp.repository.DepartmentRepository;
import com.mbbb.yygh.hosp.service.DepartmentService;
import com.mbbb.yygh.model.hosp.Department;
import com.mbbb.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    //根据医院编号和科室编号获取科室
    @Override
    public Department getDepartment(String hoscode, String depcode) {
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        return department;
    }

    //科室名称
    @Override
    public String getDeptName(String hoscode, String depcode) {

        Department department =
                departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);

        String depname = department.getDepname();

        return depname;
    }

    //根据医院编号，查询医院所有科室列表
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //创建list集合，用于最终数据封装
        List<DepartmentVo> finalData = new ArrayList<>();

        //1.根据医院编号，查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example<Department> example = Example.of(departmentQuery);
        List<Department> departmentList = departmentRepository.findAll(example);

        //2.查询所有科室转换 要求数据格式 List<Department>  -->  List<DepartmentVo>
        //把查询出来集合，根据大科室编号进行分组操作，每个大科室里面有多个小科室
        //stream流方式方便实现分组处理
        //分组之后 返回map集合，map集合key是分组大科室编号  value是每个大科室所有小科室集合
        Map<String, List<Department>> deptMap =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        //3.遍历map集合
        for (Map.Entry<String, List<Department>> listEntry : deptMap.entrySet()) {
            //大科室编号
            String bigCode = listEntry.getKey();
            //大科室编号对应的数据
            List<Department> deptSmallList = listEntry.getValue();

            //4.封装大科室
            //创建DepartmentVo对象,设置大科室数据，把多个大科室对象放到最终list集合
            DepartmentVo departmentVoBig = new DepartmentVo();
            departmentVoBig.setDepcode(bigCode); //大科室编号
            String bigname = deptSmallList.get(0).getBigname();
            departmentVoBig.setDepname(bigname); //大科室名称

            //5.封装每个大科室里面小科室
            //创建list集合用于封装每个大科室所有小科室
            List<DepartmentVo> children = new ArrayList<>();
            //List<Department> deptSmallList --> List<DepartmentVo>
            for (Department department : deptSmallList) {
                DepartmentVo departmentVoSmall = new DepartmentVo();
                departmentVoSmall.setDepcode(department.getDepcode());
                departmentVoSmall.setDepname(department.getDepname());
                children.add(departmentVoSmall);
            }

            //6.把每个大科室所有小科室放到每个大科室里面
            departmentVoBig.setChildren(children);

            //7.把多个大科室对象放到最终list集合
            finalData.add(departmentVoBig);
        }

        return finalData;
    }

    //删除科室
    @Override
    public void deleteDept(String hoscode, String depcode) {
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        if (department != null) {
            departmentRepository.deleteDeptById(department.getId());
        }
    }

    //获取分页列表
    @Override
    public Page<Department> selectPageDept(int page, int limit) {
        //设置排序
        Sort sort = Sort.by(Sort.Direction.DESC,"creatTime");
        //设置分页
        //0为第一页（当前页）
        Pageable pageable = PageRequest.of(page-1, limit, sort);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        Department department = new Department();
        department.setHoscode("10000");

        Example<Department> example = Example.of(department, matcher);

        //调用方法，分页查询
        Page<Department> pages = departmentRepository.findAll(example, pageable);
        return pages;
    }

    //上传科室
    @Override
    public void saveDepartment(Map<String, Object> stringObjectMap) {
        String jsonString = JSONObject.toJSONString(stringObjectMap);
        Department department = JSONObject.parseObject(jsonString, Department.class);

        Department existDepartment = departmentRepository.findByHoscodeAndDepcode(department.getHoscode(),department.getDepcode());

        if (existDepartment != null) {
            department.setId(existDepartment.getId());
            department.setCreateTime(existDepartment.getCreateTime());
            department.setUpdateTime(new Date());
            departmentRepository.save(department);
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            departmentRepository.save(department);
        }
    }
}
